<?php

namespace app\admin\controller\merchant;

class ProductClassify extends Base
{
    protected $model = null;

    protected $searchFields = 'name';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = loader('admin')->loadModel('tysj\\ProductClassify');
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $model = $this->model;
            $model->append(['type_text']);
            $list = $model
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        }
        $this->assign_type_options();
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $row = $this->request->post('row/a');
            $this->model->save($row);
            $this->success();
        }
        $this->assign_type_options();
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        if ($this->request->isPost()) {
            $row = $this->request->post('row/a');
            $this->model->save($row, ['id' => $ids]);
            $this->success();
        }
        $row = $this->model->where(['id' => $ids])->find();
        $this->assign('row', $row);
        $this->assign_type_options($row['type']);
        return $this->view->fetch();
    }

    //添加
    protected function assign_type_options($type = '') {
        $typeOptions = loader('admin')->loadEnum('ProductClassifyType')->get_options();
        $typeOptionsJson = json_encode_cn($typeOptions);
        $this->assign('typeOptionsJson', $typeOptionsJson);
        $typeSelect = build_select('row[type]', $typeOptions, $type, ['class' => 'form-control selectpicker']);
        $this->assign('typeSelect', $typeSelect);
    }
}
